<template>
  <div class="timeSegment h100">
    <div class="PageContent">
        <el-col :span="4" class="left-tree">
          <el-tree :data="treeTimeSegmentData" ref="timeSegTree"
                   :props="defaultProps"
                   node-key="id"
                   default-expand-all
                   check-strictly
                   highlight-current
                   @node-click="handleCheck"
          ></el-tree>
        </el-col>
        <el-col :span="20" class="right-tree">
          <el-row style="text-align: left;line-height: 5em;">
            <el-button type="primary" v-if="btnRight.btnTimeSegmentAdd" @click="addTime()">新增</el-button>
          </el-row>
          <el-row class="wrapper">
           <span v-for="(item,index) in timeSegmentTableData" class="item" @mouseenter="item.flag = true"
                 @mouseleave="item.flag = false">{{item.appointmentTimeSegment}}
              <i v-show="item.flag" @click="deleteTime(item.id,item.version)" class="item-icon el-icon-circle-close"></i>
            </span>
          </el-row>
        </el-col>
    </div>
    <el-dialog title="火化预约时间段维护" :visible.sync="dialogTimeVisibleType" width="600px"  border
               @close="closeDialog()">
        <el-row :gutter="5" v-for="(item,index) in saveFormList" style="margin-bottom: 10px;">

          <!--<el-form-item label="车辆编号:" prop="time">-->
            <!--<el-input v-model="item.startTime" ></el-input>-->
          <!--</el-form-item>-->
          <label class="labelName">输入时间段:&nbsp;
          <el-time-picker
            v-model="item.startTime"
            class="date-box"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="开始时间"
            style="width: 150px"
           >
          </el-time-picker>-
          <el-time-picker
            v-model="item.endTime"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="结束时间"
            style="width: 150px"
            >
          </el-time-picker>
          </label>
          <el-button v-if="btnRight.btnTimeSegmentAddRow" @click="deleteFormTime(index)">-</el-button>
          <el-button v-if="btnRight.btnTimeSegmentDeleteRow" @click="addFormTime()">+</el-button>
        </el-row>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button v-if="btnRight.btnTimeSegmentSave" type="primary" @click="submit()" :disabled="saveFlag">保存</el-button>
        <el-button v-if="btnRight.btnTimeSegmentCancel" type="primary" plain @click="cancelForm()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as API from '@/api/systemApplication'
  import {treeDictionaryformate} from "../../utils/treeDictionaryformate";
   export default {
    name: "timeSegment",
    data() {
      return {
        treeTimeSegmentData: [{
          label: '火化炉类型',
          children: []
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        timeSegmentTableData: [],
        tableSelection: [],
        selectedDictionaryId: 0,//选择字典id
        furnaceTypeCode: 0,//选择火化炉类型编码
        saveFlag: false, //保存标志
        onpresscTime:0,  //  阻止短时间内连续点击
        dialogTimeVisibleType: false,  //项目分类维护对话框
        saveFormList: [
          {
            "startTime": "",
            "endTime": ""
          }
        ],
        saveTimeSegment: {       //保存字典信息
          "id": 0,
          "furnaceTypeCode": "",//选择火化炉类型编码
          "startTime": "",//开始时间
          "endTime": "",//结束时间
          "version": 0,//版本
        },
        itemShow: false,
        active: {},
        rules: {
          startTime: [{required: true, message: '请输入开始时间', trigger: 'blur'}],
          endTime: [{required: true, message: '请输入结束时间', trigger: 'blur'}]
        }, btnRight: {
          btnTimeSegmentAdd: true, //新增时间
          btnTimeSegmentSave: true,//保存时间
          btnTimeSegmentCancel: true,//关闭时间
          btnTimeSegmentDelete: true,//删除时间段
          btnTimeSegmentAddRow: true,//新增行
          btnTimeSegmentDeleteRow: true,//删除行
        }
      }
    },
    mounted() {
      //载入选中字典类型
      this.loadTimeSegmentList()
      //载入按钮
      this.btnRight = this.$route.meta.buttons;
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (let key of Object.keys(this.btnRight)) {
        this.btnRight[key]=(this.btnRight[key]|| this.btnRight[key]=="true")?true:false;
      }
    },
    methods: {
      //载入火化炉类型
      loadTimeSegmentList() {
        let postData = {
          "dictCode": "furnace_type"
        }
        let this_load = this;
        API['loadDictionaryDataListWithCode'](postData).then(response => {
          const {data} = response;
          if (!data) {
            this_load.$message('数据读取失败')
            return
          }
          //格式化树
          let loadData = this_load.treeDictformate(data);
          //获得第一个返回值的children
          this_load.treeTimeSegmentData = loadData;
        }).catch(error => {
          this_load.$message(error)
        })
      }, treeDictformate(data) {
        let result = [{
          label: '火化炉类型',
          id:0,
          children: []
        }]
        if (data && data.length) {
          data.forEach(item => {
            if (item.dataText) {
              item.label = item.dataText
              item.id = item.dataCode
            }
          })
          result[0].children = data
        }
        return result
      },
      //新增时间段
      addTime() {
        this.saveTimeSegment= {       //保存字典信息
          "id": 0,
            "furnaceTypeCode": "",//选择火化炉类型编码
            "startTime": "",//开始时间
            "endTime": "",//结束时间
            "version": 0,//版本
        }
        let node = this.$refs.timeSegTree.getCheckedNodes();
        if (node && node.length){
          let this_add = this;
          //载入字典明细
          this_add.dialogTimeVisibleType = true;
        }else{
          this.$message("请选择类型")
        }
      },
      closeDialog() {
        this.dialogTimeVisibleType = false;
      },//根据明细id,version删除明细数据
      deleteTime(id, version) {
        let this_del = this;
        //删除时间段
        this.$confirm('删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData = [{
            "id": id,
            "version": version
          }];
          //载入字典明细
         API['deleteTimeSegmentWithId'](postData).then(response => {
          let data = response;
          if (!data) {
            this_del.$message(data.message)

          } else {
            this_del.$message(data.message)
          }
          //重载
          this_del.loadTimeSegmentListWithCode(this_del.furnaceTypeCode);
          return
          //加载data
          }).catch(error => {
            this_del.$message(error)
          })
        }).catch(() => {
          //几点取消的提示
        });
      },//时间段点击事件，标记哪个删除按钮该显示
      showClick: function (item) {
        // 只有有效选中的才有用
        if (item > 0) {
          this.active = item;
          this.itemShow = true;
        }else {
          this.active = 0;
          this.itemShow = false;
        }
      },
      //根据id加载物品，服务类型详情
      loadTimeSegmentListWithCode(dictCode) {
        let postData = {
          "furnaceTypeCode": dictCode
        }
        let this_load = this;
        API['loadTimeSegmentListWithCode'](postData).then(response => {
          const {data} = response;
          //console.log(data)
          if (!data) {
            this_load.$message('数据读取失败')
            return
          }
            //console.log(236)
          if (data.length && data.length > 0)
          {
            data.forEach(item=>{
              item.flag = false
            })
            this_load.timeSegmentTableData = data;

          }
          this_load.timeSegmentTableData = data;
          //获得第一个返回值的children
        }).catch(error => {
          this_load.$message(error)
        })
      },
      //火化炉类型点击事件
      handleCheck(data, checked, node) {
         // console.log(data);
        if(data.id!=0) {
          this.$refs.timeSegTree.setCheckedNodes([data]);
          node = this.$refs.timeSegTree.getCheckedNodes();
          let this_local = this;

          this_local.active = 0;
          this_local.itemShow = false;

          //记录火化炉类型编码
          this_local.furnaceTypeCode = data.id;
          //加载时间列表
          this_local.loadTimeSegmentListWithCode(data.id);
        }

      },
      selectAll(selection) {
        if (selection.length > 1) {
          selection.length = 1;
        }
        this.tableSelection = selection
      },
      //保存时间段
      submit() {
        if ((Date.now() - this.onpresscTime) > 2000) {
          this.onpresscTime = Date.now()
          console.log(Date.now())
        }else{
          return
        }
        let this_submit = this;
        let data = this.saveFormList;
        if (data.length > 0) {
          let item = {};
          let dataNew = [];
          for (let i = 0; i < data.length; i++) {
            item = data[i];
            if (item.startTime == undefined || item.startTime == "" || item.endTime == undefined || item.endTime == "") {
              this_submit.$message('开始时间或结束时间不能有为空');
              return;
            }
            let timeStr = item.startTime + '-' + item.endTime;
            dataNew.push({
              furnaceTypeCode: this_submit.furnaceTypeCode,
              appointmentTimeSegment: timeStr
            })
          }
          //发送
          let postData = dataNew;
          API['saveTimeSegment'](postData).then(response => {
            if (response) {
              let data = response;
              if (!data) {
                // this_submit.$message('数据读取失败')
                return
              }
              this_submit.dialogTimeVisibleType = true;
            }
            this_submit.saveFormList = [
              {
                "startTime": "",
                "endTime": ""
              }
            ];
            //关闭窗口
            this.dialogTimeVisibleType = false;
            //重载
            this_submit.loadTimeSegmentListWithCode(this_submit.furnaceTypeCode);
          }).catch(error => {
            this_submit.$message(error)
          });
        } else {
          this_submit.$message('时间段不能为空');
          return;
        }

      },//取消
      cancelForm() {
        this.saveTimeSegment = {}
        this.saveFormList =[
          {
            "startTime": "",
            "endTime": ""
          }
        ]
          this.dialogTimeVisibleType = false
      },//删除添加的时间框
      deleteFormTime(index) {
        if (this.saveFormList && this.saveFormList.length>1){
          this.saveFormList.splice(index,1)
        }
      },//新增时间框
      addFormTime() {
        this.saveFormList.push({
          "startTime": "",
          "endTime": ""
        })

      }
    }
  }
</script>
<style scoped>
.wrapper{
  width: 95%;
  min-height: 80%;
  max-height: 90%;
  overflow-y: auto;
  padding:20px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  justify-content: flex-start;
  background-color: white;
  border-radius: 10px;
  box-shadow:4px 4px 3px #b5b5b5;
  font-size: 16px;
}
  .wrapper .item{
    flex:0 0 120px;
    height: 50px;
    line-height: 50px;
    margin-right: 10px;
    background-color: white;
    position: relative;
  }
  .wrapper .item .item-icon{
    position: absolute;
    right: 0;
    top:16px;
    font-size: 18px;
    color: #409EFF;
  }
  .labelName{
    line-height: 40px;
    margin-right: 10px;
  }
</style>
